import * as PIXI from 'pixi.js'
import Mask from './mask'
import Sky from './sky'
import Star from './star'
// import SuperFilter from './SuperFilter'

const fragmentSrc = `
precision mediump float;
#define SHADER_NAME pixi-shader-3
varying vec2 vMaskCoord;
varying vec2 vTextureCoord;

uniform sampler2D uSampler;
uniform sampler2D mask;
uniform float alpha;
uniform float npmAlpha;
uniform vec4 maskClamp;

void main(void)
{
    vec4 masky = texture2D(mask, vMaskCoord);
    float strength =  (masky.r * masky.a);
    strength *= 5.0;
    strength = min(1.0, strength);
    vec4 original = texture2D(uSampler, vTextureCoord + (1.0- strength) * 0.2);
    gl_FragColor = original * strength;
}
`
export default class D2 {
  constructor(domElement) {
    this.loader(domElement)
  }

  loader(domElement) {
    this.loader = new PIXI.Loader()
      .add('skyBG', './assets/img/skyBG.jpg')
      .add('skyCloud1', './assets/img/skyCloud1.png')
      .add('skyCloud2', './assets/img/skyCloud2.png')
      .add('spaceBG', './assets/img/spaceBG.jpg')
      .add('sun', './assets/img/sun_add.png')
      .add('spaceCloud1', './assets/img/spaceCloud1.png')
      .add('spaceCloud2', './assets/img/spaceCloud2.png')
      .add('spaceCloud3', './assets/img/spaceCloud3.png')
      .add('blob', './assets/img/blob.png')

    this.loader.load(() => {
      this.init(domElement)
    })
  }

  init(domElement) {
    // 创建应用
    const app = new PIXI.Application({
      antialias: true, // 消除锯齿
      // backgroundAlpha: 0, // 背景不透明
      resolution: window.devicePixelRatio || 1, // 像素设置
    })
    // console.log(app)
    domElement.appendChild(app.view)
    // 应用容器宽高
    app.resizeTo = domElement

    // 屏幕容器
    const screenManager = new PIXI.Container()
    screenManager.a_info = 'screenManager'
    app.stage.addChild(screenManager)

    const mainScreen = new PIXI.Container()
    mainScreen.a_info = 'mainScreen'
    screenManager.addChild(mainScreen)

    // 天空
    const sky = new Sky()
    mainScreen.addChild(sky.view)

    // 水滴遮罩
    const mask = new Mask(app.renderer)
    mainScreen.addChild(mask)

    // 星空
    const star = new Star()
    // console.log(star.view)
    star.view.filters = [new PIXI.SpriteMaskFilter(mask)]
    star.view.filters[0].program.fragmentSrc = fragmentSrc
    mainScreen.addChild(star.view)

    // 测试失败的滤镜 错误原因：texture.castToBaseTexture is not a function
    // star.filters = [new SuperFilter(mask)]
    // console.log(star.filters[0]);

    window.addEventListener('pointermove', (event) => {
      mask.setPosition && mask.setPosition(event.clientX, event.clientY)
    })

    app.ticker.add(() => {
      sky.update()
      star.update()
      mask.update()
    })
  }
}
